/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service.impl;

import debug.Debugger;
import java.util.List;

import pojo.User;
import service.IUserService;
import util.md5Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class UserServiceImpl<T extends User> extends ServiceImpl<T>
        implements IUserService<T> {

    private String from = "ELECAward@gmail.com";
    private String TemplateName = "util/mail.txt";

    private MailSender mailSender;

    public MailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public UserServiceImpl() {
        Debugger.msg("UserServiceImpl obj created");
    }

    public T findUserByUni(String uni) {

        List<T> person = this.getDao().createQuery(
                " select u from User u "
                + " where u.unikey = :uni ").setParameter("uni", uni.trim()).list();

        if (person.size() > 0) {
            return person.get(0);
        }

        return null;
    }

    public T getUser(String uni, String password) {

        List<T> list = this.getDao().createQuery(
                " select u from User u where u.unikey = :uni "
                + " and u.password = :password").setParameter("uni", uni).setParameter("password",
                md5Util.calc(password)).list();

        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    public T updateUser(T user) {
        User old = this.findUserByUni(user.getUnikey());
        if (old == null) {
            throw new RuntimeException("invalid user");
        }
//        if (!user.getPassword().equals(old.getPassword())) {
//            user.setPassword(md5Util.calc(user.getPassword()));
//        }
        user = this.getDao().merge(user);
        this.getDao().save(user);
        return user;
    }

    public void increasePoint(T user, int points)
    {
        user.setPoints(user.getPoints()+points);
        this.getDao().save(user);
    }

    public void sendOrderMail(T user, String id, String itemName) {
		SimpleMailMessage mail = new SimpleMailMessage();
		mail.setFrom(this.from);
		mail.setTo(user.getEmail());
		mail.setSubject("Order Confirmation");
		String text = this.loadTemplateContent(TemplateName).replaceAll(
				"\\$\\{NAME\\}", user.getName());
		// mail.setText(loadTemplateContent(pwdTemplateName).replaceAll("\\$\\{LOGINNAME\\}",user.getName()));
		// mail.setText(loadTemplateContent(pwdTemplateName).replaceAll("\\$\\{PASSWORD\\}",user.getPwd()));
		text = text.replaceAll("\\$\\{ID\\}", id);
                text = text.replaceAll("\\$\\{ITEM\\}", itemName);
		mail.setText(text);
		this.mailSender.send(mail);

	}

    private String loadTemplateContent(String templateName) {
		StringBuilder sb = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(Thread
					.currentThread().getContextClassLoader()
					.getResourceAsStream(templateName), "UTF-8"));

			String lineSeparator = System.getProperty("line.separator");
			for (String str = null; (str = br.readLine()) != null;) {
				sb.append(str);
				sb.append(lineSeparator);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}

}
